package com.zjitc.service.imp;

import com.google.gson.Gson;
import com.sun.javafx.sg.prism.NGAmbientLight;
import com.zjitc.dao.OrderDao;
import com.zjitc.dao.ShippingDao;
import com.zjitc.dao.UserDao;
import com.zjitc.model.Order;
import com.zjitc.model.Shipping;
import com.zjitc.model.User;
import com.zjitc.service.OrderService;
import com.zjitc.service.ShippingService;
import com.zjitc.utils.Utils;
import com.zjitc.utils.redis.MyRedis;

import java.util.List;
import javax.jws.soap.SOAPBinding.Use;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * Create by IntelliJ IDEA
 *
 * @author: lhl
 * @date-Time: 2018/4/26 0026
 * @description:
 */
@Service
public class ShippingServiceImpl implements ShippingService {
    private Logger logger = Logger.getLogger(ShippingServiceImpl.class);
    @Autowired
    private ShippingDao shippingDao;
    @Autowired
    private MyRedis redis;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private UserDao userDao;

    @Override
    public void add(Shipping shipping) {
        shipping.setSid(Utils.getUUID());
        shippingDao.add(shipping);
        Gson gson = new Gson();
        redis.addCathc("HarvestAddresses", shipping.getUid(), gson.toJson(shipping));
    }

    @Override
    public void update(Shipping shipping) {
        String uid = shipping.getUid();
        User user = userDao.findByUid(uid);
        user.setTelephone(shipping.getShippingTelephone());
        userDao.update(user);
        List<Order> orders = redis.allOrders();
        Gson gson = new Gson();
        for (Order order : orders) {
            if (uid.equals(order.getUid())) {
                if (order.getState() == 0) {
                    order.setName(shipping.getShippingName());
                    order.setAddress(shipping.getShippingAddress());
                    order.setTelephone(shipping.getShippingTelephone());
                    orderDao.update(order);
                    redis.alertById("orders", order.getOid(), gson.toJson(order));
                }
            }
        }
        shippingDao.update(shipping);
        redis.alertById("HarvestAddresses", shipping.getUid(), gson.toJson(shipping));
    }

    @Override
    public Shipping findOne(String uid) {
        return shippingDao.findOne(uid);
    }

    @Override
    public List<Shipping> findAll() {
        return shippingDao.findAll();
    }
}
